package com.vcredit.creditcat.manager;

import com.sun.xml.bind.v2.runtime.reflect.opt.Const;
import com.vcredit.creditcat.util.Constants;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedList;

import javax.annotation.Resource;
import javax.jms.Destination;

import com.vcredit.creditcat.dto.*;
import com.vcredit.creditcat.service.*;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.net.util.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.dubbo.config.annotation.Service;
import com.vcredit.creditcat.api.IAppVersionManager;
import com.vcredit.creditcat.api.IAuthorizeManager;
import com.vcredit.creditcat.api.IPrivilegeCatManager;
import com.vcredit.creditcat.api.IResourceManger;
import com.vcredit.creditcat.dto.resource.ResourceDto;
import com.vcredit.creditcat.enumtype.AbilityEnum;
import com.vcredit.creditcat.enumtype.AccountTypeEnum;
import com.vcredit.creditcat.enumtype.AuthItemEnum;
import com.vcredit.creditcat.enumtype.CustIsRealEnum;
import com.vcredit.creditcat.enumtype.CustSourceEnum;
import com.vcredit.creditcat.enumtype.CustStatusEnum;
import com.vcredit.creditcat.enumtype.ResourceTypeEnum;
import com.vcredit.creditcat.exception.CustLoginException;
import com.vcredit.creditcat.exception.UserTempException;
import com.vcredit.creditcat.model.AppVersion;
import com.vcredit.creditcat.model.AuthIdentity;
import com.vcredit.creditcat.model.AuthItem;
import com.vcredit.creditcat.model.AuthLog;
import com.vcredit.creditcat.model.AuthProccess;
import com.vcredit.creditcat.model.Cust;
import com.vcredit.creditcat.model.CustAccount;
import com.vcredit.creditcat.model.LoginLog;
import com.vcredit.creditcat.model.PersonInfo;
import com.vcredit.creditcat.model.RegisterChannel;
import com.vcredit.creditcat.model.UserAgent;
import com.vcredit.creditcat.model.UserLogin;
import com.vcredit.creditcat.model.UserTemp;
import com.vcredit.creditcat.service.activeMQ.CommonQueueProducerService;
import com.vcredit.creditcat.service.loginPreview.SDPreviewService;
import com.vcredit.creditcat.service.loginPreview.XYHPreviewService;
import com.vcredit.creditcat.util.EnumExtUtil;
import com.vcredit.creditcat.util.Utility;
import com.vcredit.creditcat.vo.JsonResult;
import com.vcredit.framework.annotation.Log;
import com.vcredit.framework.util.BeanUtil;
import com.vcredit.framework.util.JacksonUtil;

import com.fivestars.interfaces.bbs.client.Client;
import com.fivestars.interfaces.bbs.client.Client;
import com.fivestars.interfaces.bbs.util.XMLHelper;

@Service(protocol = { "protocol1" }, version = "1.0")
public class AuthorizeManager implements IAuthorizeManager {

  @Autowired
  private CustAccountService custAccountService;
  @Autowired
  private AppTokenService appTokenService;
  @Autowired
  private CustService custService;
  @Autowired
  private LoginLogService loginLogService;
  @Autowired
  private AuthProccessService authProccessService;
  @Autowired
  private CreditCatProcessManager creditCatProcessManager;
  @Autowired
  @Qualifier(value = "ftp")
  private IResourceManger resourceManger;
  @Autowired
  private AuthIdentityService authIdentityService;
  @Autowired
  private AuthLogService authLogService;
  @Autowired
  private UserTempService userTempService;
  @Autowired
  private MessageService messageService;
  @Autowired
  private RegisterChannelService registerChannelService;
  @Autowired
  private PersonInfoService personInfoService;
  @Autowired
  private CommonQueueProducerService commonQueueProducerService;
  @Autowired
  private IAppVersionManager appVersionManager;
  @Autowired
  private XYHPreviewService xyhPreviewService;
  @Autowired
  private SDPreviewService sdPreviewService;
  @Autowired
  private UserAgentService userAgentService;
  
  @Autowired
  private IPrivilegeCatManager privilegeCatManager;

	@Resource(name = "queueDestination")
	private Destination queueDestination;

	@Value("${service.Hotline}")
	private String serviceHotline;
	@Value("${resource.down.url}")
	private String resDownUrl;

	private static Logger logger = LoggerFactory.getLogger(AuthorizeManager.class);

	/**
	 * 
	 * <p>
	 * 方法功能说明：
	 * </p>
	 * :用户登陆，静默登陆
	 * 
	 * @author
	 *         <p>
	 *         方法包含业务规则说明：
	 *         </p>
	 *         rule:
	 * @throws Exception
	 */
	@Log
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public AppLoginInfoDto appLogin(AppLoginParamDto loginParam, String appDesc,String appInfo) throws Exception {
		logger.info("appInfo"+appInfo);
		String loginName = (null == loginParam.getLoginName()) ? null : loginParam.getLoginName().trim();
		String deviceNo = (null == loginParam.getDeviceId()) ? null : loginParam.getDeviceId().trim();
		String channelCode = (null == loginParam.getChannelCode()) ? null : loginParam.getChannelCode().trim();

		AccountTypeEnum accountType = null;
		try {
			accountType = EnumExtUtil.getEnumOnValue(AccountTypeEnum.class, loginParam.getLoginType(), "code");
		} catch (Exception e) {
			e.printStackTrace();
		}
		AppLoginInfoDto appLoginInfo = new AppLoginInfoDto();
		String token = null;
		UserLogin custAccount = null;
		Cust cust = null;
		switch (accountType) {
		case MobileLogin:
			custAccount = custAccountService.login(new UserLogin(loginName, accountType.getCode()));
			if (custAccount == null) {
				custAccount = register(null, accountType, loginName, CustSourceEnum.APP, loginParam.getAppDesc(),
						channelCode);
			}

			//登陆bbs
			if (Utility.isMobileNo(loginName)) {
				String code = login(String.format("%s%d", Constants.BBS_USERNAME_PREFIX,custAccount.getCustId()), loginName.substring(5),loginName);
				appLoginInfo.setSignJs(code);
			}
			break;
		case Auto:
			custAccount = custAccountService.autoLogin(deviceNo);
			if (custAccount == null)
				throw new CustLoginException("账号已失效,或用户不存在");
			//登陆bbs
			if(null==custAccount.getUserName()){
				logger.info("username not exits");
			}else {
				String mobileNum = custAccount.getUserName();
				if (Utility.isMobileNo(mobileNum)) {
					String code = login(String.format("%s%d",Constants.BBS_USERNAME_PREFIX,custAccount.getCustId()), mobileNum.substring(5),mobileNum);
					appLoginInfo.setSignJs(code);
				}
			}
			break;
		case SynchAccount:
			CustAccount AccountParam = new CustAccount();
			AccountParam.setUserName(loginParam.getLoginName());
			List<CustAccount> targetAccount = custAccountService.find(AccountParam);
			if (Utility.isNullOrEmpty(targetAccount)) {
				throw new CustLoginException("同步账号不存在");
			}
			Long accountId = appTokenService.getAccountIdFromToken(loginParam.getAccessToken());
			// 如果原来用户身份证号与正面解析的身份证号相等，则同步账号
			Cust oldCust = custService.findByIdNo(loginParam.getIdCardNo());
			if (null != oldCust) {
				this.synchroAccount(oldCust.getCustId(), accountId);
			} else {
				throw new CustLoginException("同步信息不存在");
			}
			custAccount = custAccountService.autoLogin(deviceNo);
			break;
		default:
			throw new CustLoginException("登录方式不存在");
		}
		cust = custAccount.getCust();
		token = appTokenService.generateToken(custAccount.getAccountId(), cust.getCustId()); // 将token保存到redis中
		appTokenService.updateAppToken(token, cust.getCustId());
		loginLogService.insert(
				new LoginLog(custAccount.getAccountId(), loginParam.getDeviceId(), null, null, new Date(), token,appInfo));
		if (StringUtils.isNotBlank(cust.getCustIdno())) {
			appLoginInfo.setIsReal(CustIsRealEnum.No.getCode());
		} else {
			appLoginInfo.setIsReal(CustIsRealEnum.Yes.getCode());
		}
		appLoginInfo.setAccessToken(token);
		appLoginInfo.setRealName(cust.getCustName());
		appLoginInfo.setMobileNo(cust.getCustMobile());
		appLoginInfo.setHeadImageURL(StringUtils.isBlank(custAccount.getHeadImage()) ? null
				: (resDownUrl + "/" + custAccount.getHeadImage()));
		appLoginInfo.setServiceHotline(serviceHotline);

		// 查询版本信息
		if (StringUtils.isNotBlank(appDesc)) {
			AppVersion appVersion = appVersionManager.getAppVersion(appDesc);
			if (appDesc.indexOf("ios") != -1) {
				appLoginInfo.setAppSwitch(appVersion.getSwitchIos());
			} else {
				appLoginInfo.setAppSwitch(appVersion.getSwitchAndroid());
			}
		}
		//用户数据更新提示辅助对象
		UpdateFlagDto updateFlagDto=new UpdateFlagDto();
		Long messageId=messageService.findLatestMessage(cust.getCustId());
		if(messageId==null){
			messageId=0L;
		}
		updateFlagDto.setMessage(messageId);
		updateFlagDto.setBill(0L);
		appLoginInfo.setUpdateFlag(updateFlagDto);
		return appLoginInfo;
	}

	/**
	 * 
	 * <p>
	 * 方法功能说明：
	 * </p>
	 * :当用户不存在时，注册新用户
	 * 
	 * <p>
	 * 方法包含业务规则说明：
	 * </p>
	 * rule:
	 */
	@Log
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	protected UserLogin register(Long custId, AccountTypeEnum accountType, String userName, CustSourceEnum custSource,
			String appDesc, String channelCode) {
		if (StringUtils.isEmpty(appDesc)) {
			appDesc = "oldVersionAppDesc";
		}
		CustAccount newCustAccount = null;
		Cust newCust = null;
		newCustAccount = new CustAccount(0L, 0L, userName, accountType.getCode(), CustStatusEnum.Valid.getCode());
		newCust = new Cust();
		newCust.setCustStatus(CustStatusEnum.Valid.getCode());
		newCust.setCustSource(custSource.toString());
		custService.insert(newCust);
		newCustAccount.setCustId(newCust.getCustId());
		newCustAccount.setAccountRealname("v_" + newCust.getCustId());
		newCustAccount.setAppDesc(appDesc);
		custAccountService.insert(newCustAccount);

		// 新增客户认证流程信息
		AuthProccess creditProcess = null;
		creditProcess = authProccessService.createProcess(newCust.getCustId(), 0);
		long lastProcessId = creditProcess.getProccessId();
		custService.update(new Cust(newCust.getCustId(), lastProcessId));
		// 添加标准卡特权
		creditCatProcessManager.addAbility(AbilityEnum.Normal.getCode(), newCust.getCustId());

		UserLogin userLogin = new UserLogin();
		BeanUtil.copy(newCustAccount, userLogin);
		newCust.setCustName("v_" + newCust.getCustId());// 防止第一次注册不显示
		userLogin.setCust(newCust);
		// 渠道用户首次登陆激活
		userTempFirstLand(userName, newCust.getCustId(), channelCode);
		return userLogin;
	}

	/**
	 *
	 * <p>
	 * 方法功能说明：
	 * </p>
	 * :用户注册
	 *
	 * @author
	 *         <p>
	 *         方法包含业务规则说明：
	 *         </p>
	 *         rule:
	 */
	@Log
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void userRegister(UserRegisterParamDto registerParam, Long lastProcessId) throws Exception {
		String realName = registerParam.getRealName().trim();
		String idCardNo = registerParam.getIdStr().trim();
		CustAccount custAccount = custAccountService.findById(registerParam.getAccountId());
		if (null == custAccount) throw new CustLoginException("要注册的目标账号不存在");
		// 更新客户表
		Long custId = custAccount.getCustId();
		custAccount.setAccountRealname(realName);
		custAccount.setAccountIdno(idCardNo);
		custAccountService.update(custAccount);

		// 新增客户认证流程信息
		AuthProccess creditProcess = null;
		if (null == lastProcessId || 0 == lastProcessId) {
			creditProcess = authProccessService.createProcess(custId, 0);
			lastProcessId = creditProcess.getProccessId();
			custService.update(new Cust(custId, lastProcessId));
		}
		// 客户实名认证操作（20170726 V1.2.0 增加快速贷款、调整登录流程，去除默认注册时实名步骤，因此认证项也去除）
		//AuthItem authItem = new AuthItem();
		//authItem.setAuthCode(AuthItemEnum.REAL_NAME.getCode());
		//creditCatProcessManager.itemDone(authItem, lastProcessId);
	}

	public void userTempCheckSupplement(UserTempSmsParamDto smsParam) throws Exception {
	//    Integer XYHResult=xyhPreviewService.checkExist(smsParam.getMobileNo());
	//    if(XYHResult!=null && XYHResult.equals(0)){
		Integer SDResult = sdPreviewService.checkExist(smsParam.getMobileNo());
		if (SDResult != null && SDResult.equals(0)) {
		  throw new UserTempException("Registered");
		}
	//    }
	}

	@Log
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void headImgUpload(String headImage, Long accountId) throws Exception {
		// 头像上传
		ResourceDto resourceDto = resourceManger.upload(ResourceTypeEnum.IMG, "headImg.jpg",
				Base64.decodeBase64(headImage));
		if (null != resourceDto) {
			CustAccount custAccount = new CustAccount();
			custAccount.setAccountId(accountId);
			custAccount.setHeadImage(resourceDto.getResourceCode());
			custAccountService.update(custAccount);
		}
	}

	// 账号同步
	private void synchroAccount(Long custId, Long accountId) {
		CustAccount targetAccount = custAccountService.findById(accountId);
		targetAccount.setCustId(custId);
		custAccountService.update(targetAccount);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void signatureImgUpload(String signature, Long custId, Long lastProcessId) throws Exception {
		ResourceDto resourceDto = resourceManger.upload(ResourceTypeEnum.IMG, "signature.jpg",
				Base64.decodeBase64(signature));
		if (null != resourceDto) {
			Cust cust = new Cust();
			cust.setCustId(custId);
			;
			cust.setSignatureImage(resourceDto.getResourceCode());
			custService.update(cust);
			// 高级实名认证完成操作
			updateAuthItem(lastProcessId);
		}
	}

	// 高级实名认证完成操作
	private void updateAuthItem(Long lastProcessId) throws Exception {
		// 根据lastProcessId查询身份信息认证表信息
		AuthIdentity authIdentity = authIdentityService.findByProcessId(lastProcessId);
		AuthProccess proccess = authProccessService.findByProcessId(lastProcessId);
		if (null != authIdentity && StringUtils.isNotBlank(authIdentity.getIdFront())
				&& StringUtils.isNotBlank(authIdentity.getIdBack())
				&& StringUtils.isNotBlank(authIdentity.getIdHandheld())
		// && null != authIdentity.getHandheldCompareValue()
		) {
			// 客户身份认证操作
			AuthItem authItem = new AuthItem();
			authItem.setAuthCode(AuthItemEnum.IDENTITY_REAL.getCode());
			creditCatProcessManager.itemDone(authItem, lastProcessId);
			// 增加高级实名认证项认证日志
			authLogService
					.insert(new AuthLog(lastProcessId, proccess.getCustId(), authItem.getAuthCode(), "", new Date()));

		
		}
		if (null != authIdentity && StringUtils.isNotBlank(authIdentity.getIdFront())
				&& StringUtils.isNotBlank(authIdentity.getIdBack()) && StringUtils.isNotBlank(authIdentity.getIdFace())
				&& null != authIdentity.getLiveCompareValue()) {
			AuthItem authItem = new AuthItem();
			authItem.setAuthCode(AuthItemEnum.VERIFY_FACE_PAIR.getCode());
			creditCatProcessManager.itemDone(authItem, lastProcessId);
			// 增加人脸识别认证项认证日志
			authLogService
					.insert(new AuthLog(lastProcessId, proccess.getCustId(), authItem.getAuthCode(), "", new Date()));

		}

		//添加猫粮修改日志
		Cust cust=custService.findById(proccess.getCustId());
		//实名认证暂定类型ID=2
		privilegeCatManager.updateCustCatfood(2L, cust);

	}

	/**
	 * 渠道用户注册校验
	 * 
	 * @param smsParam
	 * @throws Exception
	 */
	@Log
	@Override
	public void userTempRegisterCheck(UserTempSmsParamDto smsParam) throws Exception {
		String channel = smsParam.getChannel();
		if (channel == null || StringUtils.isBlank(channel)) {
			throw new UserTempException("渠道不能为空");
		} else {
			List<RegisterChannel> registerChannelList = registerChannelService.findByChannel(channel);
			if (registerChannelList == null || registerChannelList.size() == 0) {
				throw new UserTempException("渠道不存在");
			}
		}
		String mobileNum = smsParam.getMobileNo();
		if (StringUtils.isNotBlank(mobileNum)) {
			List<UserTemp> userTempList = userTempService.findByMobileNum(mobileNum);
			if (userTempList == null || userTempList.size() == 0) {
				CustAccount custAccount = new CustAccount();
				custAccount.setUserName(mobileNum);
				List<CustAccount> custAccountList = custAccountService.find(custAccount);
				if (custAccountList.size() > 0) {
					throw new UserTempException("Registered");
				}
			} else {
				throw new UserTempException("Registered");
			}
		}
	}

	/**
	 * 渠道用户注册
	 * 
	 * @param loginParam
	 * @throws Exception
	 */
	@Log
	@Override
	public void userTempRegister(UserTempParamDto loginParam) throws Exception {
		String channel = loginParam.getChannel();
		String mobileNum = loginParam.getLoginName();
		String agentId = loginParam.getAgentId();
		if (StringUtils.isNotBlank(mobileNum) && StringUtils.isNotBlank(channel)) {
			UserTemp userTemp = new UserTemp();
			userTemp.setMobileNum(mobileNum);
			userTemp.setChannel(channel);
			userTempService.insert(userTemp);
		}
		if (StringUtils.isNotBlank(mobileNum) && StringUtils.isNotBlank(agentId)) {
			UserAgent userAgent = new UserAgent();
			/** 客户ID **/
			// suserAgent.setCustId(custId);
			/** 经理人ID **/
			userAgent.setAgentId(Long.parseLong(agentId));
			/** 客户手机号 **/
			userAgent.setCustPhone(mobileNum);
			/** 状态(0:默认有效，1:激活，2:失效) **/
			userAgent.setStatus(0);
			/** 来源 **/
			userAgent.setSource("");
			userAgentService.insert(userAgent);
		}
	}

	/**
	 * 渠道用户注册
	 *
	 * @param loginParam
	 * @throws Exception
	 */
	@Log
  @Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public String discuzRegister(UserTempParamDto loginParam) throws Exception {
		String signJs = "";
		Long custId = null;
		String channel = loginParam.getChannel();
		String mobileNum = loginParam.getLoginName();
		if (StringUtils.isNotBlank(mobileNum) && StringUtils.isNotBlank(channel)) {
			CustAccount account = new CustAccount();
			account.setUserName(mobileNum);
			List<CustAccount> custAccountList = custAccountService.find(account);
			if (Utility.isNullOrEmpty(custAccountList)) {//需要注册
				UserLogin custAccount = register(null, AccountTypeEnum.MobileLogin, mobileNum, CustSourceEnum.BBS, "",
						CustSourceEnum.BBS.getDesc());
				custId = custAccount.getCustId();
			}else {
				custId = custAccountList.get(0).getCustId();
			}
			if (Utility.isMobileNo(mobileNum)) {
				signJs = login(String.format("%s%d",Constants.BBS_USERNAME_PREFIX,custId), mobileNum.substring(5),mobileNum);//返回登陆JS
			}
		}
		return signJs;
	}

	@Override
	public void userTempRegisterReCheck(UserTempSmsParamDto smsParam) throws Exception {
		String mobileNo = smsParam.getMobileNo();
		String channel = smsParam.getChannel();
		int businessType = smsParam.getBusinessType();
		if (Utility.isMobileNo(mobileNo)) {
			PersonInfo param = new PersonInfo();
			param.setPersonPhone(mobileNo);
			List<PersonInfo> personInfos = personInfoService.find(param);

			if (!Utility.isNullOrEmpty(personInfos)) {
				UserTemp userTemp = new UserTemp();
				userTemp.setMobileNum(mobileNo);
				userTemp.setChannel(channel);
				userTempService.insert(userTemp);
				throw new UserTempException("Registered");
			}
		}

	}

	/**
	 * 渠道用户首次登录激活
	 * 
	 * @param mobileNum
	 * @return
	 */
	@Log
	private void userTempFirstLand(String mobileNum, Long custId, String channelCode) {
		if (StringUtils.isBlank(mobileNum)) {
			return;
		}
		UserTemp userTemp = new UserTemp();
		userTemp.setMobileNum(mobileNum);
		userTemp.setActiveStatus(Integer.valueOf(0));
		List<UserTemp> userTempList = userTempService.find(userTemp);
		if (userTempList != null && userTempList.size() > 0) {
			userTempService.firstLanding(userTempList.get(0).getUserTempId(), custId);
		}

		// 激活经理人
		UserAgent userAgent = new UserAgent();
		userAgent.setCustPhone(mobileNum);
		List<UserAgent> userList = userAgentService.find(userAgent);
		if (userList.size() > 0) {
			userAgent = new UserAgent();
			userAgent.setUserAgentId(userList.get(0).getUserAgentId());
			userAgent.setCustId(custId);
			userAgent.setStatus(1);
			userAgentService.update(userAgent);
		}else{
			userAgent = new UserAgent();
			userAgent.setCustId(custId);
			userAgent.setCustPhone(mobileNum);
			userAgent.setStatus(1);
			userAgentService.insert(userAgent);
		}
		// header 自然流量 channelCode --2017-11-16
		if (StringUtils.isNotBlank(channelCode)) {
			userTemp = new UserTemp();
			userTemp.setMobileNum(mobileNum);
			userTemp.setChannel(channelCode);
			userTemp.setActiveStatus(1);
			userTempService.insert(userTemp);
		}
	}

	/**
	 * 用户登录预检
	 * 
	 * @param mobile
	 */
	@Log
	@Override
	public void doLoginPreview(String mobile) {
		if (StringUtils.isBlank(mobile)) {
			return;
		}
		try {
			commonQueueProducerService.sendMessage(queueDestination, mobile);
		} catch (Exception e) {
			logger.error("预检消息发送出错" + mobile);
		}
	}

	// poster login creditcat bbs forume
	private String login(String userName,String pwd, String mobile){
		Client e = new Client();
		String result = e.uc_user_login(userName, pwd);
		String $ucsynlogin = "";

		LinkedList<String> rs = XMLHelper.uc_unserialize(result);
		if(rs.size()>0){
			int $uid = Integer.parseInt(rs.get(0));
			String $username = rs.get(1);
			String $password = rs.get(2);
			String $email = rs.get(3);
			if($uid > 0) {
				$ucsynlogin = e.uc_user_synlogin($uid);
			} else if($uid == -1) {
				logger.info(userName.concat("bbs用户不存在,或者被删除"));
				//直接注册
				$ucsynlogin = reg(userName,pwd,userName.concat("@vcredit.com"),mobile);
			} else if($uid == -2) {
				logger.info(userName.concat("bbs密码错"));
				//修改密码
				$ucsynlogin = resetPwd(userName, pwd, mobile);
			} else {
				logger.info(userName.concat("bbs未定义"));
			}
		}else{
			logger.info(userName.concat("Login failed"));
			logger.info(result);
		}
		return $ucsynlogin;
	}

	//regist a new poster for creditcat.forume
	private String reg(String userName, String password, String email, String mobile) {
		Client uc = new Client();
		String token = "";
		String $returns = uc.uc_user_register(userName, password ,email,mobile);
		int $uid = Integer.parseInt($returns);
		if($uid <= 0) {
			if($uid == -1) {
				logger.info(userName.concat("bbs用户名不合法"));
			} else if($uid == -2) {
				logger.info(userName.concat("bbs包含要允许注册的词语"));
			} else if($uid == -3) {
				logger.info(userName.concat("bbs用户名已经存在"));
			} else if($uid == -4) {
				logger.info(userName.concat("bbsEmail 格式有误"));
			} else if($uid == -5) {
				logger.info(userName.concat("bbsEmail 不允许注册"));
			} else if($uid == -6) {
				logger.info(userName.concat("bbs该 Email 已经被注册"));
			} else {
				logger.info(userName.concat("bbs未定义"));
			}
		} else {
			token = login(userName, password,mobile);
			logger.info(userName.concat("OK:------------------------"+$returns));
		}
		return token;
	}

	//	 	1  : 修改成功
	//	 	0  : 没有任何修改
	//	  	-1 : 旧密码不正确
	//		-4 : email 格式有误
	//		-5 : email 不允许注册
	//		-6 : 该 email 已经被注册
	//		-7 : 没有做任何修改
	//		-8 : 受保护的用户，没有权限修改
	private  String resetPwd(String userName, String pwd, String mobile){
		Client uc = new Client();
		String token = "";
		String $returns = uc.uc_user_edit(userName,"",pwd,"",1,"","");
		int $uid = Integer.parseInt($returns);
		if($uid <= 0) {
			if($uid == 0){
				logger.info(userName.concat("没有任何修改"));
			}else if($uid == -1) {
				logger.info(userName.concat("旧密码不正确"));
			} else if($uid == -2) {
				logger.info(userName.concat("包含要允许注册的词语"));
			} else if($uid == -7) {
				logger.info(userName.concat("没有做任何修改"));
			} else if($uid == -4) {
				logger.info(userName.concat("Email 格式有误"));
			} else if($uid == -5) {
				logger.info(userName.concat("Email 不允许注册"));
			} else if($uid == -6) {
				logger.info(userName.concat("该 Email 已经被注册"));
			} else if($uid == -6) {
				logger.info(userName.concat("受保护的用户，没有权限修改"));
			}else {
				logger.info(userName.concat("未定义"));
			}
		} else {
			token = login(userName, pwd, mobile);
			logger.info(userName.concat("OK:"+$returns));
		}
		return token;
	}
}
